﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;

using Silverstone.DI;

namespace Silverstone
{
    [ContentProperty("Content")]
    public class ShellBase : UserControl, IShell
    {
        private readonly IContainer container;

        public ShellBase(IContainer container)
        {
            this.container = container;
        }

        protected virtual Panel MainContainer 
        {
            get { throw new Exception("Must be implemented in derived class"); }
        }

        public void Navigate<TView>() where TView : IView
        {
            IView view = container.Get<TView>();

            if (this.MainContainer.Children.Count > 0)
            {
                UIElement oldChild = this.MainContainer.Children[0];
                this.MainContainer.Children.Remove(oldChild);

                IView oldView = oldChild as IView;
                if (oldView == null)
                {
                    throw new Exception("Invalid old view on the shell");
                }

                oldView.OnUnload();
            }

            UIElement uiElement = view as UIElement;
            if (uiElement == null)
            {
                throw new Exception("Invalid view passed to Shell.Navigate");
            }
            this.MainContainer.Children.Add(uiElement);

            view.OnLoad();
        }

        /// <summary>
        ///     Redefine the base class's content property to keep the designers happy
        /// </summary>
        public new UIElement Content
        {
            get { return base.Content; }
            set { base.Content = value; }
        }
    }
}
